<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/21
 * Time: 11:53
 */

namespace app\api\service;


use app\api\model\WorkUser;
use app\lib\enum\AuthStatusEnum;
use app\lib\exception\AuthException;
use app\lib\exception\TokenException;
use app\api\model\Work;

class BossToken extends Token
{
    /**
     * 颁发token
     * @param $code
     * @return mixed
     * @throws AuthException
     */
    public function getToken($code){
        $service = new WorkBoss();
        $userInfo = $service->getUserInfo($code);
        if (!$userInfo){
            throw new AuthException();
        }
        $info = Work::getCountInfo($userInfo->CorpId);
        $user = WorkUser::getUser($info->t_id,$userInfo->UserId);
        if ($user != null){
            if (empty($user->openID)){
                $this->userId2OpenId( $service, $info, $userInfo, $user);
            }
            $result = $this->checkAuth($user);//检查权限
            if ($result) {
                $data = $this->prepareCachedValue($user, $data = []);//准备缓存数据
                $token = $this->saveToCache($data);
                $array['token'] = $token;
                $array['tag'] = $userInfo->CorpId;//应用唯一标识
                $array['error_code'] = 0;
                $array['expire_in'] = config('setting.token_expire_in');
                return $array;
            }
           throw new AuthException();//权限不足
        }else{
            throw new AuthException([
                'code'=>404,
                'msg'=>'用户不存在',
                'error_code'=>400
            ]);
        }
    }

    /**
     * 权限检查
     * @param $user
     * @return bool
     * @throws AuthException
     */
    private function  checkAuth($user){
        if ($user->boss_power == AuthStatusEnum::ON){
            return true;
        }
        return false;
    }
    /**
     * 存储缓存，并返回token
     * @param $values
     * @return string
     * @throws TokenException
     */
    private function saveToCache($values){
        $token = self::generateToken();
        $expire_in = config('setting.token_expire_in');
        $result = cache($token,json_encode($values),$expire_in);
        if (!$result){
            throw new TokenException([
                'msg'=>'服务器缓存异常',
                'err_code'=>'10005'
            ]);
        }
        return $token;
    }

    /**
     * 准备缓存数据
     * @param $user
     * @param $data
     * @return mixed
     */
    private function prepareCachedValue($user, $data)
    {
        $data['uid'] = $user->id;
        $data['user_id'] = $user->user_id;
        $data['t_id'] = $user->t_id;
        $data['power'] = $user->boss_power;
        return $data;
    }

    /**
     * 工号与openID互换
     * @param $service
     * @param $info
     * @param $userInfo
     * @param $user
     * @return $this
     */
    private function userId2OpenId(WorkBoss $service, $info, $userInfo, $user)
    {
        $openid = $service->userIdToOpenId($info, $userInfo->UserId);
        $result = WorkUser::where('id', '=', $user->id)->update(['openID' => $openid->openid]);
        return $result;
    }
}